package com.rongshu.view.home.fragment;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.rongshu.R;
import com.rongshu.eventbus.JPushMessage;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.DateUtils;
import com.rongshu.utils.LoginUtils;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseFragment;
import com.rongshu.view.home.contract.UserInfoView;
import com.rongshu.view.home.entity.ShareInformation;
import com.rongshu.view.home.entity.UserInfo;
import com.rongshu.view.home.presenter.UserInfoPresenter;
import com.rongshu.view.login.activity.QuestionFeedbackActivity;
import com.rongshu.view.login.activity.VerificationCodeLoginActivity;
import com.rongshu.view.submitArticle.activity.SweepQRCodeActivity;
import com.rongshu.view.userInfo.activity.AddVCertificationActivity;
import com.rongshu.view.userInfo.activity.ArticleActivity;
import com.rongshu.view.userInfo.activity.AttentionAcitivity;
import com.rongshu.view.userInfo.activity.BrowsingHistoryActivity;
import com.rongshu.view.userInfo.activity.CardBagActivity;
import com.rongshu.view.userInfo.activity.EnshrineActivity;
import com.rongshu.view.userInfo.activity.FansActivity;
import com.rongshu.view.userInfo.activity.IntimacyAnnouncementActivity;
import com.rongshu.view.userInfo.activity.InvitationActivity;
import com.rongshu.view.userInfo.activity.MessageClassifyActivity;
import com.rongshu.view.userInfo.activity.NewsGuideActivity;
import com.rongshu.view.userInfo.activity.PayActivity;
import com.rongshu.view.userInfo.activity.PenpalWillActivity;
import com.rongshu.view.userInfo.activity.PerfectInfomationActivity;
import com.rongshu.view.userInfo.activity.PersonDetailsActivity;
import com.rongshu.view.userInfo.activity.RecommendActivity;
import com.rongshu.view.userInfo.activity.RecyclerStationActivity;
import com.rongshu.view.userInfo.activity.SettingActivity;
import com.rongshu.view.userInfo.activity.ShareActivity;
import com.rongshu.view.userInfo.activity.SignActivity;
import com.rongshu.view.userInfo.dialog.ChiefExperienceOfficerDialog;
import com.rongshu.view.userInfo.entity.AccountInformation;
import com.rongshu.view.userInfo.entity.MessageInfo;
import com.rongshu.widget.PraiseNumDialog;
import com.rongshu.widget.ShareBottomDialog;
import com.rongshu.widget.YNestedScrollView;
import com.utils.DensityUtil;
import com.utils.ShadowDrawable;
import com.utils.permissions.OnPermission;
import com.utils.permissions.Permission;
import com.utils.permissions.XXPermissions;
import com.widget.CircleImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;
import static com.rongshu.utils.UserInfoUtils.getUserId;

/**
 * description：个人中心页面
 */
public class UserInfoFragment extends BaseFragment<UserInfoPresenter> implements UserInfoView {
    @BindView(R.id.layout_setting)
    RelativeLayout layout_setting;
    @BindView(R.id.nested_scroll_view)
    YNestedScrollView nested_scroll_view;
    @BindView(R.id.iv_head_icon)
    CircleImageView iv_head_icon;
    @BindView(R.id.iv_vip)
    ImageView iv_vip;
    @BindView(R.id.txt_vip)
    TextView txt_vip;
    @BindView(R.id.txt_user_name)
    TextView txt_user_name;
    @BindView(R.id.iv_chief)
    ImageView iv_chief;
    @BindView(R.id.txt_add_v)
    ImageView txt_add_v;
    @BindView(R.id.txt_attention_num)
    TextView txt_attention_num;
    @BindView(R.id.txt_fans_num)
    TextView txt_fans_num;
    @BindView(R.id.txt_get_like_num)
    TextView txt_get_like_num;
    @BindView(R.id.txt_pen_pal_will_num)
    TextView txt_pen_pal_will_num;
    @BindView(R.id.txt_remaining_sum)
    TextView txt_remaining_sum;
    @BindView(R.id.txt_card_sum)
    TextView txt_card_sum;
    @BindView(R.id.txt_message_sum)
    TextView txt_message_sum;
    @BindView(R.id.layout_edit)
    LinearLayout layout_edit;
    @BindView(R.id.layout_login)
    LinearLayout layout_login;
    @BindView(R.id.layout_function)
    LinearLayout layout_function;
    //map
    private Map<String, Object> map = null;
    //intent
    private Intent intent = null;
    //用户基本信息
    private UserInfo.ResponseBean userInfo = null;
    //扫描二维码成功返回
    public static int SWEEP_QRCODE_LOGIN = 101;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragemnt_userinfo;
    }

    @Override
    protected void initViews() {
        //padding
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) layout_setting.getLayoutParams();
        layoutParams.topMargin = DensityUtil.getStateBar(getActivity()) * 3 / 4;
        layout_setting.setLayoutParams(layoutParams);
        //set presenter
        setPresenter(new UserInfoPresenter(getActivity()), this);
        //添加阴影
        ShadowDrawable.setShadowDrawable(layout_function,
                ContextCompat.getColor(getActivity(), R.color.white),
                (int) getResources().getDimension(R.dimen.dd_dimen_16px),
                ContextCompat.getColor(getActivity(), R.color.transparent_zone_point_one),
                (int) getResources().getDimension(R.dimen.dd_dimen_16px),
                0, 0);
        //eventBus
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @Override
    public void onResume() {
        super.onResume();
        //user_id
        int user_id = getUserId();
        layout_edit.setVisibility(user_id == 0 ? View.GONE : View.VISIBLE);
        layout_login.setVisibility(user_id == 0 ? View.VISIBLE : View.GONE);
        if (user_id != 0) {
            getUserInfo(user_id);
            getAccountModel(user_id);
            getMsgCount();
        } else {
            cleanUserInfo();
        }
    }

    /**
     * 获取用户资料
     */
    public void getUserInfo(int user_id) {
        map = new HashMap<>();
        map.put("user_id", user_id);
        presenter.getUserInfo(user_id, Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 账户信息
     */
    public void getAccountModel(int user_id) {
        map = new HashMap<>();
        map.put("user_id", user_id);
        presenter.getAccountModel(user_id, Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 分享APP
     */
    public void shareApp() {
        //user_id
        int user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin(getActivity());
            return;
        }
        map = new HashMap<>();
        map.put("user_id", user_id);
        presenter.getShareUrl(user_id, Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 获取我的消息页面的未读信息数
     */
    public void getMsgCount() {
        //user_id
        int user_id = getUserId();
        if (user_id == 0) {
            return;
        }
        map = new HashMap<>();
        map.put("user_id", user_id);
        presenter.getMsgCount(user_id, Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 用户基本信息
     *
     * @param responseBean
     */
    private void updateUserBaseInformation(UserInfo.ResponseBean responseBean) {
        if (responseBean == null) {
            return;
        }
        this.userInfo = responseBean;
        //头像
        RequestOptions options = new RequestOptions()
                .centerCrop()
                .placeholder(R.drawable.user_head_icon);
        Glide.with(getActivity())
                .load(responseBean.getAvatar())
                .apply(options)
                .into(iv_head_icon);
        //首席
        String reg_time = responseBean.getReg_time();
        long registration_date = DateUtils.parseDate(DateUtils.YYYY_MM_DD, reg_time).getTime();
        String time = "2019-02-25";
        long reduced_date = DateUtils.parseDate(DateUtils.YYYY_MM_DD, time).getTime();
        if (registration_date <= reduced_date) {
            iv_chief.setVisibility(View.VISIBLE);
        } else {
            iv_chief.setVisibility(View.GONE);
        }
        //vip
        boolean isVip = responseBean.isVip();
        iv_vip.setVisibility(isVip ? View.VISIBLE : View.GONE);
        txt_add_v.setVisibility(isVip ? View.GONE : View.VISIBLE);
        txt_vip.setVisibility(isVip ? View.VISIBLE : View.GONE);
        if (isVip) {
            txt_vip.setText(responseBean.getVipText());
        }
        //name
        txt_user_name.setText(responseBean.getBi_name());
    }

    /**
     * 账号信息
     */
    private void updateAccountInformation(AccountInformation.ResponseBean information) {
        if (information == null) {
            return;
        }
        //关注数
        txt_attention_num.setText(information.getGuanzhu() + "");
        //粉丝数
        txt_fans_num.setText(information.getFensi() + "");
        //获赞
        txt_get_like_num.setText(information.getArticleLikeCount() + "");
        //笔友会
        txt_pen_pal_will_num.setText(information.getPenPalwillCount() + "");
        //卡包
        txt_card_sum.setText(information.getCard_bag() + "张");
//        //剩余榕树叶
//        txt_remaining_sum.setText(information.getRead_fenshu() + "");
    }

    @OnClick({R.id.layout_setting_center, R.id.iv_head_icon, R.id.layout_attention, R.id.layout_fans,
            R.id.layout_pen_pal_will, R.id.layout_article, R.id.layout_invitation, R.id.layout_recommend,
            R.id.layout_share, R.id.layout_collect, R.id.layout_recycler, R.id.layout_browsing_history,
            R.id.layout_qrCode, R.id.layout_message_center, R.id.layout_get_like, R.id.layout_edit,
            R.id.layout_login, R.id.layout_card, R.id.layout_feedback_to_help, R.id.layout_recommend_to_friends,
            R.id.layout_account_remaining_sum, R.id.layout_intimacy, R.id.sign_layout, R.id.txt_add_v, R.id.iv_chief,
            R.id.layout_news_guide})
    public void onClick(View view) {
        //user_id
        int user_id = UserInfoUtils.getUserId();
        switch (view.getId()) {
            case R.id.layout_setting_center:
                if (user_id == 0) {
                    LoginUtils.toLogin(getContext());
                    return;
                }
                intent = new Intent(getActivity(), SettingActivity.class);
                if (userInfo != null) {
                    intent.putExtra(Constant.INTENT_DATA, userInfo.getMobile());
                }
                startActivity(intent);
                break;
            case R.id.iv_head_icon://头像
                if (user_id == 0) {
                    LoginUtils.toLogin(getContext());
                    return;
                }
                intent = new Intent(getActivity(), PersonDetailsActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_edit://编辑资料
                if (user_id == 0) {
                    LoginUtils.toLogin(getContext());
                    return;
                }
                intent = new Intent(getActivity(), PerfectInfomationActivity.class);
                if (userInfo != null) {
                    intent.putExtra(Constant.INTENT_DATA, userInfo.getUser_id());
                }
                startActivity(intent);
                break;
            case R.id.layout_account_remaining_sum://账户余额
                if (user_id == 0) {
                    LoginUtils.toLogin(getContext());
                    return;
                }
                intent = new Intent(getActivity(), PayActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_card://我的卡包
                if (user_id == 0) {
                    LoginUtils.toLogin(getContext());
                    return;
                }
                intent = new Intent(getActivity(), CardBagActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_attention://我的关注
                if (user_id == 0) {
                    LoginUtils.toLogin(getContext());
                    return;
                }
                intent = new Intent(getActivity(), AttentionAcitivity.class);
                startActivity(intent);
                break;
            case R.id.layout_fans://我的粉丝
                if (user_id == 0) {
                    LoginUtils.toLogin(getContext());
                    return;
                }
                intent = new Intent(getActivity(), FansActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_pen_pal_will://笔友会
                if (user_id == 0) {
                    LoginUtils.toLogin(getContext());
                    return;
                }
                intent = new Intent(getActivity(), PenpalWillActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_article://我的文章
                if (user_id == 0) {
                    LoginUtils.toLogin(getContext());
                    return;
                }
                intent = new Intent(getActivity(), ArticleActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_invitation://我的帖子
                if (user_id == 0) {
                    LoginUtils.toLogin(getContext());
                    return;
                }
                intent = new Intent(getActivity(), InvitationActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_recommend://我的推荐
                if (user_id == 0) {
                    LoginUtils.toLogin(getContext());
                    return;
                }
                intent = new Intent(getActivity(), RecommendActivity.class);
                intent.putExtra(Constant.USER_ID, getUserId());
                startActivity(intent);
                break;
            case R.id.layout_share://我的分享
                if (user_id == 0) {
                    LoginUtils.toLogin(getContext());
                    return;
                }
                intent = new Intent(getActivity(), ShareActivity.class);
                intent.putExtra(Constant.USER_ID, getUserId());
                startActivity(intent);
                break;
            case R.id.layout_collect://我的收藏
                if (user_id == 0) {
                    LoginUtils.toLogin(getContext());
                    return;
                }
                intent = new Intent(getActivity(), EnshrineActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_recycler://回收站
                if (user_id == 0) {
                    LoginUtils.toLogin(getContext());
                    return;
                }
                intent = new Intent(getActivity(), RecyclerStationActivity.class);
                if (userInfo != null) {
                    intent.putExtra(Constant.INTENT_DATA, userInfo.getMobile());
                }
                startActivity(intent);
                break;
            case R.id.layout_browsing_history://浏览记录
                if (user_id == 0) {
                    LoginUtils.toLogin(getContext());
                    return;
                }
                intent = new Intent(getActivity(), BrowsingHistoryActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_qrCode:
                if (user_id == 0) {
                    LoginUtils.toLogin(getContext());
                    return;
                }
                toSweepQRCode();
                break;
            case R.id.layout_message_center://消息中心
                if (user_id == 0) {
                    LoginUtils.toLogin(getContext());
                    return;
                }
                intent = new Intent(getActivity(), MessageClassifyActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_get_like://获赞
                if (user_id == 0) {
                    LoginUtils.toLogin(getContext());
                    return;
                }
                String prarseNum = txt_get_like_num.getText().toString().trim();
                if (TextUtils.isEmpty(prarseNum)) {
                    return;
                }
                PraiseNumDialog.Builder builder = new PraiseNumDialog.Builder(getActivity());
                builder.setPrarseNum(Integer.parseInt(prarseNum));
                PraiseNumDialog praiseNumDialog = builder.create();
                praiseNumDialog.show();
                break;
            case R.id.layout_login://去登录
                intent = new Intent(getActivity(), VerificationCodeLoginActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_feedback_to_help://反馈
                if (user_id == 0) {
                    LoginUtils.toLogin(getContext());
                    return;
                }
                intent = new Intent(getActivity(), QuestionFeedbackActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_recommend_to_friends://分享给好友
                if (user_id == 0) {
                    LoginUtils.toLogin(getContext());
                    return;
                }
                shareApp();
                break;
            case R.id.layout_intimacy://亲密榜
                intent = new Intent(getActivity(), IntimacyAnnouncementActivity.class);
                startActivity(intent);
                break;
            case R.id.sign_layout://签到
                if (user_id == 0) {
                    LoginUtils.toLogin(getContext());
                    return;
                }
                intent = new Intent(getActivity(), SignActivity.class);
                startActivity(intent);
                break;
            case R.id.txt_add_v://加v
                if (user_id == 0) {
                    LoginUtils.toLogin(getContext());
                    return;
                }
                if (userInfo == null) {
                    return;
                }
                String bi_name = userInfo.getBi_name();
                String mobile = userInfo.getMobile();
                boolean vip = userInfo.isVip();
                int state = userInfo.getState();
                if (vip) {//0审核中 1通过 2驳回
                    if (state == 0) {
                        toast("加v审核中");
                        return;
                    }
                    if (state == 1) {
                        toast("加v通过");
                        return;
                    }
                }
                intent = new Intent(getActivity(), AddVCertificationActivity.class);
                intent.putExtra(Constant.INTENT_MESSAGE, bi_name);
                intent.putExtra(Constant.INTENT_DATA, mobile);
                intent.putExtra(Constant.INTENT_TYPE, vip);
                startActivity(intent);
                break;
            case R.id.iv_chief:
                ChiefExperienceOfficerDialog.Builder builder1 = new ChiefExperienceOfficerDialog.Builder(getActivity());
                ChiefExperienceOfficerDialog dialog = builder1.create();
                dialog.show();
                break;
            case R.id.layout_news_guide://新手指南
                startActivity(new Intent(getActivity(), NewsGuideActivity.class));
                break;
        }
    }

    /**
     * 扫码
     */
    public void toSweepQRCode() {
        if (!XXPermissions.isHasPermission(getActivity(), Permission.CAMERA)) {
            XXPermissions.with(getActivity())
                    .permission(Permission.CAMERA)
                    .request(new OnPermission() {

                        @Override
                        public void hasPermission(List<String> granted, boolean isAll) {
                            Intent intent = new Intent(getActivity(), SweepQRCodeActivity.class);
                            startActivityForResult(intent, SWEEP_QRCODE_LOGIN);
                        }

                        @Override
                        public void noPermission(List<String> denied, boolean quick) {
                            XXPermissions.gotoPermissionSettings(getActivity());
                        }
                    });
        } else {
            Intent intent = new Intent(getActivity(), SweepQRCodeActivity.class);
            startActivityForResult(intent, SWEEP_QRCODE_LOGIN);
        }
    }

    /**
     * 用户基本信息回调
     *
     * @param userInfo
     */
    @Override
    public void onUserInfo(UserInfo userInfo) {
        if (userInfo.getErrCode() == 0) {
            updateUserBaseInformation(userInfo.getResponse());
        }
    }

    /**
     * 分享信息
     *
     * @param response
     */
    @Override
    public void onShareApp(ShareInformation response) {
        if (response.getErrCode() == 0) {
            final ShareInformation.ResponseBean bean = response.getResponse();
            if (bean == null) {
                return;
            }
            ShareBottomDialog.Builder builder = new ShareBottomDialog.Builder(getActivity());
            builder.setShareData(bean);
            builder.create().show();
        } else {
            toast(response.getErrMsg());
        }
    }

    /**
     * 账号信息
     *
     * @param information
     */
    @Override
    public void onAccountInfo(AccountInformation information) {
        if (information.getErrCode() == 0) {
            updateAccountInformation(information.getResponse());
        }
    }

    /**
     * 未读消息数
     *
     * @param info
     */
    @Override
    public void onMsgCount(MessageInfo info) {
        if (info.getErrCode() == 0) {
            MessageInfo.ResponseBean bean = info.getResponse();
            if (bean != null) {
                int count = bean.getAllMsgCount();
                txt_message_sum.setVisibility(count > 0 ? View.VISIBLE : View.GONE);
                txt_message_sum.setText(count > 99 ? "···" : String.valueOf(count));
            }
        } else {
            toast(info.getErrMsg());
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == SWEEP_QRCODE_LOGIN) {
                if (data != null) {
                    String stringExtra = data.getStringExtra(Constant.SWEEP_QRCODE_RESULT);
                    presenter.loginPC(stringExtra, UserInfoUtils.getUserId());
                }
            }
        }
    }

    /**
     * 清空页面数据
     */
    private void cleanUserInfo() {
        //用户信息
        userInfo = null;
        //头像
        iv_head_icon.setImageResource(R.drawable.user_head_icon);
        iv_vip.setVisibility(View.GONE);
        //关注数
        txt_attention_num.setText("0");
        //粉丝数
        txt_fans_num.setText("0");
        //获赞
        txt_get_like_num.setText("0");
        //笔友会
        txt_pen_pal_will_num.setText("0");
        //消息
        txt_message_sum.setVisibility(View.GONE);
        //剩余榕树叶
        txt_remaining_sum.setText("0");
        //卡包
        txt_card_sum.setText("0张");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            //user_id
            int user_id = getUserId();
            layout_edit.setVisibility(user_id == 0 ? View.GONE : View.VISIBLE);
            layout_login.setVisibility(user_id == 0 ? View.VISIBLE : View.GONE);
            if (user_id != 0) {
                getUserInfo(user_id);
                getAccountModel(user_id);
            } else {
                //清空原有数据
                cleanUserInfo();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 接收推送消息
     */
    @Subscribe
    public void onJPushMessage(JPushMessage jPushMessage) {
        getMsgCount();
    }
}
